 
Page({
  data: {
    messageList: [],
    inputValue: "如何提高消费质量？",
    resultA: "",
    url_token: "https://aip.baidubce.com/oauth/2.0/token?client_id=62KVdvaY3tBlWtdf8zo5vhbK&client_secret=TNRzOtZ56Az1gVA8eT4ZAlLNHoVeP1GC&grant_type=client_credentials",
    url_chat: "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=24.03733c2069b294ead3fde2f67cd5ffa3.2592000.1718608379.282335-71787051"
  },

  onLoad: function () {
    wx.setNavigationBarTitle({
        title: '财富小助手机器人',
      })
    this.getToken();
  },
 
  getToken(){
    const payload = {
      "messages": [
        {
           "role": "user",
           "content": "你在一个理财小游戏里扮演理财小助手的角色，用来回答玩家关于理财方面的问题。语气要亲切一点，回答要简短！！这是你的开场白：你好，我是你的理财小助手，有关理财方面的问题请向我提问，我会尽力为你解答~"
        }
      ]
    };
    wx.request({
      url: this.data.url_chat,
      method: "POST",
      data: payload,
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
       this.setData({
         resultA: res.data.result
       })
              
      },
    });
  },
   
  

  sendMessage: function (e) {
    if (this.data.inputValue.match(/^[ ]*$/)) {
      wx.showModal({
        title: '不能发送空白信息',
        showCancel: false,
      })
    } else {
      const payload = {
        "messages": [
          {
             "role": "user",
             "content": this.data.inputValue
          }
        ]
      };
      wx.showLoading({
        title: '加载中',
      })
      var that = this
      this.data.messageList.push({
        tx: this.data.inputValue,
        rx: 'loading...'
      })
      this.createSelectorQuery().select('.scroll-wrap').node(function (res) {
        let ScrollViewContext = res.node
        ScrollViewContext.scrollIntoView(`#tx-item-${that.data.messageList.length - 1}`)
      }).exec()
      wx.request({
        url: this.data.url_chat,
        method: "POST",
        data: payload,
        header: {
          'Content-Type': 'application/json'
        },
        success:(res => {
          let messageList = this.data.messageList
          console.log(res.data.result)
          messageList[messageList.length-1].rx = res.data.result
          console.log("res.data.result")
          this.setData({
            messageList: messageList,
            inputValue: ""
          })
          this.createSelectorQuery().select('.scroll-wrap').node(function (res) {
            let ScrollViewContext = res.node
            ScrollViewContext.scrollIntoView(`#rx-item-${that.data.messageList.length - 1}`)
          }).exec()
          wx.hideLoading()
        }),
        fail:(res =>{
          wx.showModal({
            title: '分析失败',
            content: err,
          })
        })
      });
    }
  }
});